import request from './lib/request'
import cheerio from 'cheerio'
// import moment from 'moment'
import model from './model'

import event from './lib/event'

async function crawler3(startTime, endTime, start) {
  const response = await request({
    methods: 'get',
    url: '/manage/apUser/toPending',
    params: {
      status: 1,
      start: start,
      registerStartDate: startTime,
      registerEndDate: endTime
    }
  })

  var $ = cheerio.load(response)

  let html = $('.table').html()
  html = html.substring(html.indexOf('</tbody>') + 8)

  const page = $(html).find('tr').map(function() {
    let id = $($(this).find('td').eq(0).first().html()).attr('id')
    const row = $(this).find('td').map(function(item) {
      return $(this).text().replace(/(^\s*)|(\s*$)/g, '')
    })
    return {
      id: id,
      userName: row[2], // 账号
      registerTime: row[3], // 注册时间
      userGroup: row[4],
      grabPosition: 'toAppIncomplete'
    }
  })

  for (let i = 0; i < page.length; i++) {
    const element = page[i]
    await model.insert(element)
    event.emit('processed')
  }

  let nextStart = start - 20
  if (nextStart > 0) {
    crawler3(startTime, endTime, nextStart)
  } else if (start !== 0) {
    crawler3(startTime, endTime, 0)
  }
}

async function crawler2(startTime, endTime) {
  const response = await request({
    methods: 'get',
    url: '/manage/apUser/toPending',
    params: {
      status: 1,
      registerStartDate: startTime,
      registerEndDate: endTime
    }
  })

  var $ = cheerio.load(response)
  const temp = $('.pager').text().match(/[\d]+/g)
  event.emit('total', parseInt(temp[0]))
  crawler3(startTime, endTime, temp[0] - 20)
}

function crawler(startTime) {
  // crawler2(startTime, moment().format('YYYY-MM-DD HH:MM:SS'))
  crawler2(startTime, null)
}

export default crawler
